package com.matrix.im.domain.model;

import lombok.Data;
import org.springframework.data.annotation.Id;
import org.springframework.data.annotation.Transient;
import org.springframework.data.mongodb.core.index.CompoundIndex;
import org.springframework.data.mongodb.core.mapping.Document;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author 有点甜
 * @since 2025/8/2
 */
@Data
@Document(collection = "conversations")
@CompoundIndex(name = "user_pair_idx", def = "{'user1Id': 1, 'user2Id': 1}", unique = true)
public class Conversation {
    @Id
    private String id;
    private Long user1Id;
    private Long user2Id;

    private String lastMessageContent;
    private String lastMessageType;
    private Long lastMessageFromUserId;
    private Date lastMessageTimestamp;
    private Integer user1UnreadCount = 0;
    private Integer user2UnreadCount = 0;

    @Transient
    private List<ChatMessage> messages = new ArrayList<>();

    private Conversation() {}

    public static Conversation create(Long user1Id, Long user2Id) {
        Conversation conversation = new Conversation();
        if (user1Id < user2Id) {
            conversation.user1Id = user1Id;
            conversation.user2Id = user2Id;
        } else {
            conversation.user1Id = user2Id;
            conversation.user2Id = user1Id;
        }
        return conversation;
    }

    public void receiveNewMessage(ChatMessage message) {
        this.lastMessageContent = message.getContent();
        this.lastMessageType = message.getMessageType();
        this.lastMessageFromUserId = message.getFromUserId();
        this.lastMessageTimestamp = message.getTimestamp();

        if (user1Id.equals(message.getToUserId())) {
            this.user1UnreadCount++;
        } else if (user2Id.equals(message.getToUserId())) {
            this.user2UnreadCount++;
        }
        this.messages.add(message);
    }

    public void markAsRead(Long readerId) {
        if (user1Id.equals(readerId)) {
            this.user1UnreadCount = 0;
        } else if (user2Id.equals(readerId)) {
            this.user2UnreadCount = 0;
        }
    }

    public Integer getUnreadCountForUser(Long userId) {
        if (user1Id.equals(userId)) {
            return this.user1UnreadCount;
        } else if (user2Id.equals(userId)) {
            return this.user2UnreadCount;
        }
        return 0;
    }
}
